// pages/post/post.js
const app = getApp(), core = require('../../utils/core'), util = require('../../utils/util'), WeValidator = require('../../utils/we-validator');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    job: {type:1},
    jobCategories: [],
    categoryPath: '',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let page = this;
    let jobId = options.id;
    util.getJobCategories().then(categories => {
      page.setData({jobCategories: categories});
      if(jobId) {
        core.get({url:'/xilujob.job_manage/edit/id/'+jobId, success(ret) {
          let job = ret.data.job;
          for(let key in job.job_info) {
            if(job.job_info.hasOwnProperty(key)) {
              job[key] = job.job_info[key]
            }
          }
          delete job['job_info'];
          page.setData({job: job});
        }});
      }else {
        core.get({url:'/xilujob.job_manage/add', success: ret => {
          page.setData({job: ret.data.job});
        }});
      }
    });
  },
  bindJobTypeChange: function (event) {
    this.setData({'job.type': event.currentTarget.dataset.type});
    console.log(this.data.job);
  },
  bindJobNameInput: function (event) {
    this.setData({'job.job_name': event.detail.value});
  },
  bindNumInput: function (event) {
    this.setData({'job.num': event.detail.value});
  },
  bindJobCategoryChange: function (event) {
    let selectedItems = event.detail.items, selectedItem = selectedItems[selectedItems.length-1];
    if(event.detail.isManual) {
      this.setData({'job.job_category_id': selectedItem.id});
    }
    // 设置显示名称
    let path = [];
    selectedItems.forEach(function(item){
      path.push(item.category_name);
    });
    path = path.join(' | ');
    this.setData({categoryPath: path});
  },
  bindNextStep: function () {
    let job = this.data.job;
    let validator = new WeValidator({
      rules: {
        type: {required:true,range:[1,2]},
        job_name: {required:true},
        num: {required:true,digits:true},
        job_category_id: {required:true}
      },
      messages: {
        type: {required:'请选择职位类型', range:'请选择职位类型'},
        job_name: {required:'请填写职位名称'},
        num: {required:'请填写招聘人数',digits:'招聘人数请填写正整数'},
        job_category_id: {required:'请选择职位分类'}
      }
    });
    if(!validator.checkData(job)) {
      return;
    }
    wx.navigateTo({url: '/pages/post1/post1', success: res => {
      res.eventChannel.emit("jobTransfer", this.data.job);
    }});
  },

});
